package com.nxzh.de.executor.config.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.lang.Nullable;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源
 * 
 * @author ruoyi
 */
public class DynamicDataSource extends AbstractRoutingDataSource
{
    @Nullable
    private Map<Object, Object> bakTargetDataSources;

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
    {
        this.bakTargetDataSources = targetDataSources;
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey()
    {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }

    public void putTargetDataSources(Map<Object, Object> targetDataSources) {
//        Optional.ofNullable(targetDataSources).orElseThrow(() -> new Exception (" don ' send a null"));
        this.bakTargetDataSources.putAll(targetDataSources);
        super.setTargetDataSources(bakTargetDataSources);
        super.afterPropertiesSet();
    }
}